package com.yzg.simple.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * @author misterWei
 * @mailbox mynameisweiyan@gmail.com
 *
 *  基于NIO 群聊系统 客户端实现
 */
public class ChatClient {

    private final String HOST_NAME = "127.0.0.1";
    private Selector selector;
    private SocketChannel socketChannel;
    private static final Integer PORT = 6868;

    public ChatClient(){
        try {
           selector =  Selector.open();
            socketChannel = SocketChannel.open(new InetSocketAddress(HOST_NAME,PORT));
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    //去监听服务端给的消息
    public void monitor(){
        try {
            int i = selector.select();
            if (i > 0){
                Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();
                while (selectionKeyIterator.hasNext()){
                    SelectionKey selectionKey = selectionKeyIterator.next();
                     if (selectionKey.isReadable()){
                         SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                         ByteBuffer allocate = ByteBuffer.allocate(1024);
                         socketChannel.read(allocate);
                         System.out.println(new String(allocate.array()));
/*
                         selectionKeyIterator.remove();
*/
                     }

                }
                selectionKeyIterator.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {

        }
    }

    public void sendMes(String info){
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //发送消息
    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        new Thread(){
            @Override
            public void run(){
                while (true){
                    try {
                        chatClient.monitor();
                        Thread.sleep(2000);
                    }catch (InterruptedException e ){

                    }
                }
            }

        }.start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String mes = scanner.nextLine();
            chatClient.sendMes(mes);
        }
    }



}
